<!--
 * @Description: 
 * @Author: mmzhang
 * @Date: 2022-04-15 12:01:51
 * @LastEditTime: 2022-08-24 11:26:28
-->
<template>
  <div>
    <dt-modal-edit ref="edit" title="编辑产证客户" @ok="onOk" :width="800" :transfer="true">
      <dt-grid ref="table" :columns="columns" :list="cusList" :heightResize="true">
      </dt-grid>
      <div class="add-btn" @click="addBtnFun">+ 增加一个产证客户</div>
    </dt-modal-edit>
  </div>
</template>
<script>
  import columnConfig from './customer'
  import contractMgr from '@/biz/sales/contractOrder.js'
  export default {
    props: ['contractId'],
    data() {
      return {
        columns: [],
        cusList: [],
        delIdList: []
      }
    },
    methods: {
      show(showList) {
        let cusList = JSON.parse(JSON.stringify(showList))
        cusList.forEach(ele => {
          for (let key in ele) {
            ele[key] = ele[key] == '-' ? '' : ele[key]
          }
          ele.areaCodes = []
          ele.areaNames = []
          if (ele.provinceCode != '' && ele.provinceCode != '-' && ele.provinceCode !=
            null) {
            ele.areaCodes.push(ele.provinceCode)
            ele.areaNames.push(ele.provinceName)
          }
          if (ele.cityCode != '' && ele.cityCode != '-' && ele.cityCode != null) {
            ele.areaCodes.push(ele.cityCode)
            ele.areaNames.push(ele.cityName)
          }
          if (ele.areaCode != '' && ele.areaCode != '-' && ele.areaCode != null) {
            ele.areaCodes.push(ele.areaCode)
            ele.areaNames.push(ele.areaName)
          }

        });

        let _this = this;
        Promise.all([contractMgr.getProvinceList()]).then(() => {
          this.$refs.edit.show()
          this.$refs.table.init(this)
          this.cusList = [...cusList]
          this.columns = columnConfig.options(this)
          setTimeout(() => {
            _this.$refs.table.loadList(this.cusList)
          }, 500);
        })
      },
      resetFun() {
        this.columns = columnConfig.options(this)
      },
      checkRepeat(Arr) {
        let set = new Set();
        let result = [];
        let len = Arr.length;
        for (let i = 0; i < len; i++) {
          let setLen = set.size;
          set.add(Arr[i]);
          //若集合调用add方法后，集合的size没有变化，则说明该元素为重复的数字
          if (setLen == set.size) {
            result.push(Arr[i]);
          }
        }
        return Array.from(new Set(result));
      },
      onOk() {
        let reg =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

        // 校验客户手机号不能重复
        const newArr = this.cusList.map(item => {
          return item.customerPhone
        })

        let repeatPhone = this.checkRepeat(newArr)

        if (repeatPhone.length) {
          this.$Message.error('产证客户手机号不能相同')
          this.cusList.forEach(item => {
            if (repeatPhone.indexOf(item.customerPhone) > -1) {
              item.customerPhone = ''
            }
          })
          return false
        }

        try {
          this.cusList.forEach(ele => {
            // 客户名称
            if (ele.customerName == '' || ele.customerName == null) {
              this.$Message.error('请检查，客户名称不能为空')
              throw Error();
            }
            if (ele.customerName.length > 20) {
              this.$Message.error('请检查，客户名称字长小于等于20个汉字或等量字符')
              throw Error();
            }
            // 手机号
            if (ele.customerPhone == '' || ele.customerPhone == null) {
              this.$Message.error('请检查，手机号不能为空')
              throw Error();
            }
            if (ele.customerPhone.length != 11) {
              this.$Message.error('请输入正确的手机号')
              throw Error();
            }
            // 证件号码
            if (ele.credentialsNumber.length > 30) {
              this.$Message.error('请检查，证件号码字长小于等于30位字符')
              throw Error();
            }

            //邮政编号
            if (ele.postalCode.length > 10) {
              this.$Message.error('请检查，邮政编号字长小于等于10位字符')
              throw Error();
            }

            //地址
            if (ele.detailedAddress.length > 250) {
              this.$Message.error('请检查，详细地址字长小于等于250个汉字或等量字符')
              throw Error();
            }
          })
        } catch (e) {
          return false
        }

        let params = {
          contractId: this.contractId,
          addOrEditOrProduceEvidenceList: this.cusList.filter(item => {
            if (item.areaCodes.length) {
              item.provinceCode = item.areaCodes[0]
              item.cityCode = item.areaCodes[1]
              item.areaCode = item.areaCodes[2]
            } else {
              item.provinceCode = ''
              item.cityCode = ''
              item.areaCode = ''
            }
            item.provinceName = item.provinceName == '-' ? '' : item.provinceName
            item.cityName = item.cityName == '-' ? '' : item.cityName
            item.areaName = item.areaName == '-' ? '' : item.areaName
            return item
          }),
          delIdList: this.delIdList
        }

        contractMgr
          .batchEditOrProduceEvidenceFun(params)
          .then((res) => {
            this.$Message.success('修改成功')
            this.$refs.edit.hide()
            this.$emit('onSearch')
          })
          .catch((res) => {
            this.$refs.edit.hide()
            this.$emit('onSearch')
          })
      },
      onDeleteFun(row) {
        if (this.cusList.length == 1) {
          this.$Message.info('至少保留一个产证客户')
          return false
        }
        this.$Modal.confirm({
          title: '删除',
          content: '确认删除此产证客户？',
          closable: true,
          onOk: () => {
            for (let i = this.cusList.length - 1; i >= 0; i--) {
              if (this.cusList[i]._XID == row._XID) {
                if (this.cusList[i].id) {
                  this.delIdList.push(this.cusList[i].id)
                }
                this.cusList.splice(i, 1)
              }
            }
          },
          onCancel: () => {},
        })
      },
      addBtnFun() {
        let obj = {
          contractId: this.contractId,
          customerName: '',
          produceType: 0,
          customerPhone: '',
          credentialsType: null,
          credentialsNumber: '',
          postalCode: '',
          provinceCode: '',
          areaCode: '',
          cityCode: '',
          areaCodes: [],
          detailedAddress: '',
        }
        this.cusList.push(obj)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .add-btn {
    height: 48px;
    border: 1px solid #e8eaec;
    border-top: 0;
    text-align: center;
    line-height: 48px;
    cursor: pointer;
  }

  // cascader控件去检查元素后发现是在input框的placeholder里面
  ::v-deep .ivu-cascader .ivu-input::-webkit-input-placeholder {
    color: #515a6e !important;
  }
</style>